#!/usr/bin/node

const log = console.log,
  fs = require('fs'),
  http = require('http'),
  https = require('https'),
  url = require('url'),
  cheerio = require('cheerio'),
  add = 'https://maoyan.com/films?showType=3';

function getPage() {

  let html = fs.readFileSync('./index.html');
  html = html.toString().replace('/getdata', 'http://localhost:8081/getlist');

  return html;
}

let movielist = [];
let opt = url.parse(add);
opt.headers = {
  'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36'
}

https.get(opt, (res) => {
  let data = '';

  res.on('data', (chunk) => { data += chunk; });
  res.on('end', () => {

    let $ = cheerio.load(data);
    let courses = $('body').find('div.movie-item-title>a');
    let score = $('body').find('div.channel-detail-orange');

    for (let i = 0; i < courses.length; i++) {
      let movies = {
        movieId: '',
        movieName: '',
        movieRange: ''
      }

      let num = $(courses[i]).attr('href').lastIndexOf('/');

      movies.movieName = $(courses[i]).text();
      movies.movieId = $(courses[i]).attr('href').substring(num + 1);
      movies.movieRange = $(score[i]).text();
      movielist[i] = movies;
    }
  })
})

http.createServer((req, res) => {
  let addr = url.parse(req.url);

  if (addr.pathname == '/') {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/html');
    res.end(getPage());
    return;
  }
  if (addr.pathname == '/getlist') {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/json');
    res.end(JSON.stringify(movielist));
    return;
  }

}).listen(8081);
